<?php
/**
 * Created by PhpStorm.
 * User: lance
 * Date: 2017/10/31
 * Time: 16:07
 */

namespace app\leader\admin;

use app\common\builder\ZBuilder;
use app\common\log\addRole\ManagerAdd;
use app\common\log\createAccount\CreateManager;
use app\manager\admin\ManagerException;
use app\manager\model\Manager;
use think\Db;
use app\admin\controller\Admin;

/**
 * 领导添加
 * Class Import
 * @package app\manager\admin
 */
class Import extends Admin
{
    public function add()
    {
        if (request()->isAjax()):
            $o_validate = new \app\manager\validate\Manager();
            //验证数据
            if ($o_validate->check(input('')) === FALSE):
                $this->error($o_validate->getError());
            endif;
            //保存数据
            $o_model = new Manager();
            Db::startTrans();
            try {
                //step1 添加领导
                if (!$o_model->insert(input(''))):
                    throw new ManagerException('添加失败！');
                endif;
                $i_managerId = $o_model->getLastInsID();
                //step2 分配领导账号
                $a_data = [
                    'username' => input('number'),
                    'nickname' => input('number'),
                    'email' => input('email'),
                    //TODO 领导初始密码位身份证后六位
                    //password' => substr(input('cert_number'), -6),
                    'password' => 123456,
                    'mobile' => input('tel_number'),
                    'role_id' => $i_managerId,
                    'status' => 1,
                    'role' => 2,
                ];
                if (($s_msg = CreateManager::addOne($a_data)) !== true) :
                    throw new ManagerException($s_msg);
                endif;
                Db::commit();
                //step3 记录添加领导日志
                $o_log = new ManagerAdd([
                    'role_id' => $i_managerId,
                    'status' => 1,
                    'error' => '',
                    'role_type' => 3,
                    'content' => json_encode(input(''))
                ]);
                $o_log->addOne();
                $this->success("添加成功!");
            } catch (ManagerException $e) {
                Db::rollback();
                //记录错误日志
                $o_log = new ManagerAdd([
                    'role_id' => 0,
                    'status' => 0,
                    'role_type' => 3,//领导
                    'error' => $e->getErrorMsg(),
                    'content' => json_encode(input(''))
                ]);
                $o_log->addOne();
                $this->error($e->getErrorMsg());
            }
        else:
            //提示信息
            $s_tips = <<<EOT
1.手动添加领导。<br/>
2.领导帐号为柜员号，初始密码为123456,登录后可修改。
EOT;

            return ZBuilder::make('form')
                ->addHidden('type',1)
                ->setPageTips($s_tips)
                ->addFormItems(Config('manager_info'))
                ->fetch();
        endif;
    }
}